<template>
	<view class="page b-f">
		<view class="courseware_list_box">
			<block v-if="showType<2"><!-- 文件列表 -->
				<view v-for="(fileItem, fileIndex) in coursewareList" :key="fileIndex" class="courseware_item" @tap="bindCourseware(fileItem)">
					<view class="courseware_info">
						<view class="file_img_box">
							<image class="file_img" :src="imgPrefix(getCoverImg(fileItem.file||fileItem.src))"></image>
							<block v-if="fileItem.status&&(fileItem.status==1||fileItem.status==2)">
								<view v-if="fileItem.status==1" class="status_style dis-flex flex-y-center flex-x-center"><text class="weui-loading"></text></view>
								<view v-else-if="fileItem.status==2" class="status_style dis-flex flex-y-center flex-x-center"><image class="err_icon" :src="imgPrefix('/static/image/teacher/err_icon.png')"></image></view>
							</block>
						</view>
						<view class="file_info onelist-hidden">
							<view class="file_name onelist-hidden">{{fileItem.filename}}</view>
							<view class="file_message red" v-if="fileItem.status==2">上传失败</view>
							<view class="file_message" v-else>{{setFileSize(fileItem.size)}} {{setTime(fileItem.createtime,'yyyy.MM.dd hh:ss')}}上传</view>
						</view>
					</view>
					<view class="operation">
						<!-- <text v-if="fileItem.status==1" class="weui-loading"></text>
						<text v-else-if="fileItem.status==2" class="del_icon">上传失败</text> -->
						<view v-if="showType == 0" class="big_icon" @click.stop="bindDelFile(fileItem.teacher_file_id)">
							<image class="del_icon" :src="imgPrefix('/static/image/icon/teacher_card_close.png')"></image>
						</view>
						<view v-else class="big_icon" @click.stop="bindSelectCourseware(fileIndex,!fileItem.select)">
							<image class="select_icon" :src="fileItem.select? imgPrefix('/static/image/teacher/status_1.png'):imgPrefix('/static/image/icon/address_status_0.png')"></image>
						</view>
					</view>
				</view>
			</block>
			<block v-else>
				<view v-for="(studentItem, studentIndex) in studentList" :key="studentIndex" class="courseware_item">
					<view class="courseware_info">
						<image class="file_img" :src="studentItem.avatar"></image>
						<view class="file_info onelist-hidden">
							<view class="file_name onelist-hidden">{{studentItem.nickname}}</view>
							<view class="file_message">最近上课:{{studentItem.time}}</view>
						</view>
					</view>
					<view class="operation">
						<image @tap.stop="bindSelectStudent(studentIndex)" class="select_icon" :src="studentItem.select? imgPrefix('/static/image/teacher/status_1.png'):imgPrefix('/static/image/icon/address_status_0.png')"></image>
					</view>
				</view>
			</block>
			<load-more :status="loadState" :text="(showType==0?'暂无上传文件':'您暂无授课学生')"></load-more>
		</view>
		
		<fixed-bottom>
		<view class="fixed_bottom">
			<view @tap="bindShare" :class="['border_btn', showType == 0 ? '' : 'border_btn_gery']">{{ showType == 0 ? '分享课件' : showType == 1 ? '取消分享':'返回' }}</view>
			<view @tap="showType == 0 ? bindUpload() :showType == 1 ? bindToShare():bindShareCourseware()" class="active_btn">{{ showType == 0 ? '上传课件' :showType ==1 ? '去分享':'点击分享' }}</view>
		</view>
		</fixed-bottom>
	</view>
</template>

<script>
const app = getApp();
import { random_string,format,deepClone } from '@/static/uitls/common.js';
import { changeFormat } from '@/static/mixins/changeFormat.js';
import API from '@/static/api/index.js';
import loadMore from '@/components/loadmore/index.vue';
let downloadTask = '';
export default {
	name: 'teacher-my-courseware',
	mixins: [changeFormat],
	components: {
		loadMore
	},
	data() {
		return {
			uploadIndex:0,//判断是否在上传状态 避免弹出选择文件后进入onshow 为0时没有 其它值为当前上传数
			loadState:'loading',
			showType:0, //显示类型 0 默认列表 1 点击分享课件 2 学生列表
			noMore: false,
			isDown: false, // 当前是否在下载
			coursewareList: [
				// {
				// 	filename: 'ppt名称',
				// src/file 文件路径
				// 	stutas:0, // 没有或0 已经成功上传  1 上传中 2 上传失败
				// size:1,
				// 	select:0
				// }
			],
			page:1,
			size:10,
			totals:0,
			isRequest:false,
			studentList:[],
			storageFileList:[]//本地存储的数据
		};
	},
	computed:{
		selectcoursewareId:function(){ // 选出选择了的文件数组
			let {coursewareList}=this;
			let arr =[]
			coursewareList.filter(o=>o.select==true).forEach(e=>{
				arr.push(e.teacher_file_id)
			})
			return arr;
		},
		selectStudentId:function(){ // 选出选择了的学生数组
			let {studentList}=this;
			let arr =[]
			studentList.filter(o=>o.select==true).forEach(e=>{
				arr.push(e.user_id)
			})
			return arr;
		}
	},
	onLoad() {
		this.refresh();
		if(!uni.getStorageSync('file_list')){//没有就初始化
			uni.setStorageSync('file_list',JSON.stringify([]))
		}
		this.storageFileList = JSON.parse(uni.getStorageSync('file_list'));
	},
	onPullDownRefresh() {
		if(this.showType<2){
			this.page==1
			this.refresh();
		}else{
			this.bindToShare()
		}
	},
	onReachBottom() {
		if(this.uploadIndex==0){//
			this.isRequest=false
			this.getTCoursewareList()
		}
	},
	methods: {
	
		// 获取封面图片
		getCoverImg(file){
			let extension = this.getExtensionName(file)
			let formatName='';
			if(extension.indexOf("doc")!=-1){
				formatName = 'word'
			}else if(extension.indexOf("ppt")!=-1||extension.indexOf("pptx")!=-1){
				formatName = 'ppt'
			}else if(extension.indexOf("xlsx")!=-1||extension.indexOf("exe")!=-1||extension.indexOf("EXE")!=-1){
				formatName = 'excel'
			}else if(extension.indexOf("pdf")!=-1){
				formatName = 'pdf'
			}
			return '/static/image/teacher/'+formatName+'.png'
		},
		// 获取文件容量
		setFileSize(size){
			let sizeText = '';
			if(size>(1024*1024)){
				sizeText =parseFloat((size/1024/1024).toFixed(2))+'MB'
			}else if(size>1024){
				sizeText = parseFloat((size/1024).toFixed(2))+'KB'
			}else{
				sizeText = size+'B'
			}
			return sizeText;
		},
		
		// 刷新
		refresh(showOnload=true){
			app._log(123)
			setTimeout(()=>{
				if(this.uploadIndex==0){ // 没有上传中或上传失败的，避免选择文件后进入
					app._log(456)
					this.isRequest=false
					this.page=1
					this.getTCoursewareList(showOnload)
				}
			},1000)
		},
		
		// 文件分页请求
		getTCoursewareList(showOnload=true){
			let {isRequest,page,size,coursewareList}=this;
			if(!isRequest&&(coursewareList.length<this.totals||page==1)){
				this.isRequest=true
				this.loadState = 'loading'
				API.getTCoursewareList(page,size,showOnload).then(({code,data})=>{
					if(code==1){
						data.files.forEach(e=>{
							e.select=false
						})
						let tempArr = (page==1?[]:coursewareList).concat(deepClone(data.files));
						this.coursewareList = tempArr;
						this.$forceUpdate();
						this.totals = data.total;
						this.loadState = tempArr.length>=data.total?'nomore':'getmore';
						if(data.total>tempArr.length){
							this.page+=1
						}
					}else if(code==405&&page==1){
						this.loadState = 'empty'
						this.coursewareList= []
					}else{
						this.loadState = 'error'
					}
					app._log(code,data)
					this.isRequest=false
				}).catch(err=>{
					this.isRequest=false
					this.loadState = 'error'
				})
			}
		},
		// 点击分享
		bindShare(){
			let {coursewareList,showType}=this;
			if(coursewareList.length>0||showType==1){
				this.showType = showType==0?1:0;
			}else if(coursewareList.length==0){
				this.showToast('您暂无课件')
			}
		},
		// 点击选择文件
		bindSelectCourseware(index,status){
			app._log(index,status)
			this.coursewareList[index].select = status;
		},
		// 点击选择学生
		bindSelectStudent(index){
			this.studentList[index].select = !this.studentList[index].select;
		},
		// 点击分享课件
		bindShareCourseware(){
			let {selectcoursewareId,selectStudentId}=this;
			if(selectStudentId.length==0){
				this.showToast('暂未选择您要分享的学生')
			}else{
				API.shareTCourseware({user_id:selectStudentId,teacher_file_id:selectcoursewareId}).then(({code,data,msg})=>{
					if(code==1){
						uni.showModal({
							title:'分享成功',
							content:'是否返回文件列表？',
							success: (res) => {
								if(res.confirm){
									this.showType=0
								}
							}
						})
					}else{
						this.showToast(msg||'分享失败')
					}
				}).catch(err=>{
					this.showToast(err.msg||'分享失败')
				})
			}
		},
		
		// 页面点击图片上传
		bindUpload() {
			let _this = this;
			let {coursewareList,size}=this;
			let checkForamt = ['doc', 'ppx', 'xls', 'xlsx', 'docx', 'pdf', 'pptx'];
			wx.chooseMessageFile({
			  count: 10,
			  type: 'file',
			  extension:checkForamt,
				success:({tempFiles})=> {
					app._log(tempFiles)
					const defNum = coursewareList.length;
					let newArr = tempFiles.filter(o=>checkForamt.findIndex(extension=>('.'+extension)==this.getExtensionName(o.path))!=-1); // 找出满足格式条件的
					if(tempFiles.length!=newArr.length){
						this.showToast('请上传正确格式的文件')
					}
					if(newArr.length>0){
						newArr.forEach(({name,path,size})=>{
							coursewareList.unshift({filename: _this.getDefultName(name),src:path,stutas:1,select:0,size:size,createtime:format(new Date(),'yyyy-MM-dd hh:ss')}) //stutas 没有或0 已经成功上传  1 上传中 2 上传失败
						})
						this.coursewareList = coursewareList;
						this.$forceUpdate();
						this.loadState=defNum+newArr.length>size?'getmore':'nomore';
						this.uploadIndex+=newArr.length // 修改上传文件数量
						 newArr.forEach(({name,path,size}) => {
							try {
								_this.fileUpload({path:path,name:_this.getDefultName(name)},(src, state, file = '') => {
									app._log(path,'本地路径',src,'文件路径',file)
									_this.sendTCourseware(_this.getDefultName(name),size,file,src,state);//将文件路径等信息上传到服务器
								});
							} catch (e) {
								//TODO handle the exception
							}
						 });
					}
			  },
			  fail:(err) => {
			  	this.showToast('取消选择');
			  	app._log(err);
			  }
			})
		},
		
		//文件上传成功后将文件信息上传到服务器
		sendTCourseware(filename,size,file,src,state,success,fail){ //文件名   大小 线上路径  本地路径 文件状态  成功回调 失败回调
			let _this = this;
			API.sendTCourseware({filename:filename,size:size,file:file}).then(res=>{
				if(res.code==1){
					app._log('本地路径',src,'文件路径',file)
					let fileIndex = _this.coursewareList.findIndex(o=>o.src==src);
					if(state){
						this.totals+=1
					}
					if(fileIndex!=-1){
						_this.coursewareList[fileIndex].stutas = state ? 0 : 2;
						if (file != '') {
							_this.coursewareList[fileIndex].file = file;
							_this.coursewareList[fileIndex].teacher_file_id = res.data;
						}
					}
					this.uploadIndex-=1
					if(this.uploadIndex==0){
						this.refresh();
					}
					success&&success(res)
				}else{
					this.showToast(res.msg||'文件上传失败')
					fail&&fail(res)
				}
			}).catch(err=>{
					this.showToast(err.msg||'文件上传失败')
				app._log(err)
					fail&&fail(err)
			})
		},
		// 单文件上传
		fileUpload(obj, success) { //obj ==>{path,name}
		let {path}=obj
			this.isRequest=true
			this.getSign(
				obj,
				sres => {
					//获取签名
					app._log('签名成功', sres);
					this.uploadFile(
						sres,
						(state, file) => { // 文件上传
							app._log('文件上传成功', path, state, file);
							success(path, state, file);
						},
						uerr => {
							app._log('文件上传失败', uerr);
							success(path, false);
						}
					);
				},
				serr => {
					app._log('获取签名失败', serr);
					success(path, false); // 获取签名失败
				}
			);
		},
		// 给将要上传的文件oss签名
		getSign({path,name}, callback, fail) {
			API.ossSign().then(({ code, data, msg }) => {
				if (code == 1) {
					let { accessid, dir, expire, host, policy, signature } = data;
					callback && callback({ file: path, url: host, key: dir + name+new Date().valueOf()+this.getExtensionName(path), policy: policy, OSSAccessKeyId: accessid, signature: signature });
				} else {
					// app._log(msg)
					this.showToast(msg);
					fail && fail(path);
				}
			})
			.catch(err => {
				app._log(err);
				this.showToast('文件上传失败，请联系管理员');
				fail && fail(path);
			});
		},
		// 上传单文件到oss
		uploadFile({ url, file, key, policy, OSSAccessKeyId, signature }, success, fail) {
			uni.uploadFile({
				url: url,
				name: 'file',
				filePath: file,
				formData: {
					key: key,
					policy: policy,
					OSSAccessKeyId: OSSAccessKeyId,
					success_action_status: '200', //让服务端返回200,不然，默认会返回204
					signature: signature
				},
				success: res => {
					app._log(res);
					if (res.statusCode == 200) {
						success && success(true, url + '/' + key); // 返回状态和线上链接
					} else {
						fail && fail(false);
					}
				},
				fail: err => {
					app._log(err);
					fail && fail(false);
				}
			});
		},

		// 获取文件原名
		getDefultName(file){
			// app._log(file)
			return file.substring(0,file.lastIndexOf('.'));
		},
		// 获取文件后缀
		getExtensionName(file){
			return file.substring(file.lastIndexOf('.'), file.length);
		},
		// 生成随机文件名称并返回
		// returnFileName(file) {
		// 	app._log(file)
		// 	return random_string(18)+this.getExtensionName(file);
		// },

		// 点击去分享
		bindToShare(){
			let {coursewareList}=this;
			if(coursewareList.length==0){
				this.showToast('当前暂无文件')
			}else{
				let arr= coursewareList.filter(o=>o.select==true)
				if(arr.length==0){
					this.showToast('请选择分享文件')
				}else{
					this.showType =2
							this.loadState='loading';
					API.getTStudentList().then(({code,data})=>{
						if(code==1){
							data.users.forEach(e=>{
								e.select=false
							})
							this.studentList = data.users;
							this.loadState=data.users.length==0?'empty':'nomore';
						}else{
							this.studentList = []
							this.loadState=data.length==0?'empty':'error';
							this.showToast(data.length==0?'暂无学生列表':'获取学生列表失败')
						}
					}).catch(err=>{
							this.studentList = []
						app._log(err)
							this.loadState='error';
						this.showToast('获取学生列表失败')
					})
				}
			}
		},
		
		// 点击删除文件
		bindDelFile(id){
			uni.showModal({
				title:'删除提醒',
				content:'确定删除该课件吗？',
				success: (res) => {
					if(res.confirm){
						this.showToast('删除成功')
						API.deleteTCourseware(id).then(({code,msg})=>{
							app._log(code,msg)
							if(code==1){
								this.showToast('删除成功')
								let tempArr = this.coursewareList;
								let index = tempArr.findIndex(o=>o.teacher_file_id==id);
								if(index!=-1){
									tempArr.splice(index,1);
									this.coursewareList = tempArr;
								}
								this.refresh(false)
							}else{
								this.showToast(msg||'删除失败')
							}
						}).catch(err=>{
							this.showToast('删除失败')
						})
					}
				}
			})
		},
		
		
		//判断数组对象中有没有存在某个键值
		JudgingISExistence(arr,keyName,keyData){  //数组 键名 键值
			return arr.findIndex(o=>o[keyName]==keyData)			
		},
		
		
		// 点击下载文件 ==》1
		bindCourseware({state,file,size,filename}) {
			if(state==1){
				this.showToast('文件上传中')
				return false
			}else if(state==2){
				this.showToast('文件上传失败')
				return false
			}
			let _this = this;
			let {storageFileList } = _this;
			let index = this.JudgingISExistence(storageFileList,'file',file);
			app._log('存在不',index)
			if(index!=-1){ // 已经下载过该文件
			
				let {tempFilePath,savedFilePath}=storageFileList[index]
				if(savedFilePath!=''){//有本地文件路径
					uni.getFileInfo({
						filePath:savedFilePath,
						success: (res) => {
							app._log('下载过该文件了',res)
							if(res.errMsg=='getFileInfo:ok'){ // 文件存在
								this.openDocument(savedFilePath);//直接打开
							}else{ //有记录但是文件丢失等报错
								this.startDownloading(file,size,filename) // 开始下载
							}
						},
						fail:err=>{ // 文件丢失等原因重新下载
							this.startDownloading(file,size,filename) // 开始下载
						}
					})
				}else if(tempFilePath!=''){//有临时文件路径
					_this.saveFile(file,size,tempFilePath,filename);//保存并打开文件
				}else{
					this.startDownloading(file,size,filename) // 开始下载
				}
			}else{ // 没有下载过该文件
				if(size>1024*1024*9){
					uni.setClipboardData({
						data: file.toString(),
						success: res => {
							this.showToast('复制成功，请在浏览器打开');
						},
						catch: err => {
							this.showToast('复制失败');
						}
					});
				}else{
					this.startDownloading(file,size,filename) // 开始下载
				}
			}
		},
		
		 // 开始下载==》2
		startDownloading(file,size,filename){
			let _this = this;
			let { isDown } = _this;
			if (isDown) {
				this.showToast('您当前正在下载，请稍后再试');
			} else {
				this.showToast('正在下载'+filename);
				_this.isDown = true;
				this.clearFile({fileSize:size,clearType:0},status=>{
					this.downFide(file,size,filename)
				})
			}
		},
		//清除已下文件
		clearFile({fileSize,clearType},success){//clearType 0 容量达到临界清除  1 直接清除  fileSize文件大小
			uni.getSavedFileList({
				success:({errMsg='',fileList=[]})=>{
					app._log(errMsg,fileList)
					if(errMsg=='getSavedFileList:ok'){
						app._log(errMsg,fileList)
						app._log('已经下载了的文件列表',fileList);
						let maxSize = 0;
						if(clearType==0&&fileList.length>0){ //达到临界清除和文件不为空
							fileList.forEach(e=>{
								maxSize+=e.size;
							})
						}
						if(clearType==1||clearType==0&&Number(maxSize+fileSize)<=6*1024*1024){ // 容量超了或者强制清除
							fileList.forEach(e=>{
								uni.removeSavedFile({filePath: e.filePath});
							})
							this.storageFileList=[]
						}
						success&&success(true)
					}else{
						success&&success(false)
					}
				},
				fail:err=>{
					app._log(err);
					success&&success(false)
				}
			});
		},
		// 文件清除失败
		clearError(file,size,filename){
			this.clearFile({clearType:0},status=>{
				app._log(status)
				if(status){ // 清除成功
					// this.bindCourseware({status,file,size,filename})
				}
			})
		},
		 // 单文件下载
		downFide(file,size,filename){
			let _this=this;
			downloadTask = uni.downloadFile({
				url:file,
				success: ({ statusCode, tempFilePath }) => {
					if (statusCode === 200) {
						app._log('下载成功',tempFilePath);
						_this.storageFileList.push({ file:file, tempFilePath:tempFilePath, savedFilePath: '' });
						_this.isDown = false;
						_this.saveFile(file,size,tempFilePath,filename);//保存并打开
					} else {
						_this.showToast('下载失败');
						_this.isDown = false;
					}
				},
				fail: err => {
					app._log(err);
					_this.showToast('下载失败');
					_this.isDown = false;
				}
			});
			// downloadTask.onProgressUpdate((res) => {
			// 	app._log('下载进度' + res.progress);
			// 	app._log('已经下载的数据长度' + res.totalBytesWritten);
			// 	app._log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
			// });
		},
		// 保存单文件并打开
		saveFile(file,size,tempFilePath,filename){
			let _this = this;
			uni.saveFile({
				tempFilePath,
				success: ({ savedFilePath }) => {
					_this.openDocument(savedFilePath)
					let index = _this.JudgingISExistence(_this.storageFileList,'file',file);
					if(index!=-1){
						_this.storageFileList[index].savedFilePath = savedFilePath;
					}
				},
				fail: err => {
					app._log('文件保存失败',err)
					this.clearError(file,size,filename)
				}
			});
		},
		//打开文件
		openDocument(path){
			uni.openDocument({
				filePath: path,
				success: respon => app._log('成功打开文档')
			});
		},
		// 中断下载任务
		abort() {
			downloadTask.abort();
		}
	},
	onHide(){
		uni.setStorageSync('file_list',JSON.stringify(this.storageFileList.filter(o=>o.savedFilePath!='')))
	},
	beforeDestroy() {
		if(this.isDown){
			downloadTask.abort();
		}
	}
};
</script>

<style scoped lang="scss">
.page{
	padding-bottom: calc(114rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(114rpx + env(safe-area-inset-bottom));
}
.file_info{margin-left: 24rpx;}
.courseware_item,
.file_info,
.fixed_bottom {
	display: flex;
	justify-content: space-between;
}
.file_info .red{
	color: red!important;
}
.courseware_list_box {
	padding: 8rpx 48rpx;
	.courseware_item {
		width: 654rpx;
		height: 148rpx;
		background-color: #f8f8f8;
		border-radius: 16rpx;
		padding: 24rpx;
		align-items: center;
		margin-top: 24rpx;
		.courseware_info {
			display: flex;
			flex: 1;
			.file_img {
				width: 96rpx;
				height: 96rpx;
				background-color: #d35230;
				border-radius: 8rpx;
			}
			.file_img_box{
				margin-right: 24rpx;
				position: relative;
				width: 96rpx;
				height: 96rpx;
				.err_icon{
					width: 56rpx;
					height: 56rpx;
				}
			}
			.status_style{
				position: absolute;
				width: 100%;
				height: 100%;
				background-color: rgba(0,0,0,0.3);
				border-radius: 4px;
				z-index: 1111;
				top: 0;
				margin-right: 24rpx;
			}
			.file_info {
				flex-direction: column;
				.file_name {
					width: 384rpx;
					font-size: 32rpx;
					line-height: 44rpx;
					color: #252748;
				}
				.file_message {
					width: 372rpx;
					font-size: 26rpx;
					line-height: 36rpx;
					color: #ababac;
				}
			}
		}
		.operation {
			.big_icon{
				padding: 20rpx 22rpx;
			}
			.del_icon {
				width: 40rpx;
				height: 40rpx;
			}
			.select_icon {
				width: 44rpx;
				height: 44rpx;
			}
		}
	}
}
.fixed_bottom {
	width: 750rpx;
	height: 114rpx;
	background-color: #fff;
	padding: 12rpx 48rpx;
	.border_btn {
		width: 192rpx;
		line-height: 92rpx;
		text-align: center;
		background-color: #ffffff;
		border-radius: 16rpx;
		color: #7f4aff;
		border: solid 2rpx #7f4aff;
		margin-right: 24px;
	}
	.border_btn_gery {
		color: #8f8f9a;
		border: solid 2rpx #8f8f9a;
	}
	.active_btn {
		color: #fff;
		text-align: center;
		width: 438rpx;
		line-height: 92rpx;
		background-image: linear-gradient(270deg, #7f4aff 0%, #9254ff 100%);
		border-radius: 16rpx;
	}
}
</style>
